﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
using KFGame;
 

public class StartScene : MonoBehaviour
{
    // Start is called before the first frame update
    private NetWork net;

    private authorization authorization;
    bool isnet = false;


    public string nextScene = "LogoScene";
    public Text deid;
    public Text LoadingTip;
    public GameObject loadingview;
    public GameObject loginview;
    public InputField username;
    public InputField password;

    public Text LoginTip;


    public GameObject authorzview;
    public InputField authorzCode;


    public GameObject longcheckObject;

    public GameObject reauthorzview;

    string server;

    void Awake()
    {

    }

    void Start()
    {

        if (Application.isEditor)
        {
            gotoPlay();
            return;
        }



        server = KF.kf.config.server;

        deid.text = "";

        loadingview.SetActive(true);

        net = new NetWork();
        net.doEvnet += Event;

        //isnet = net.checkNet();GetRequest
        checknet();

        authorization = new authorization();


        StartCoroutine(startform());


    }

    public IEnumerator startform()
    {
        yield return new WaitForSeconds(2f);
        //无锁走安装流程
        if (!authorization.isLock())
        {
            tograntAU();

        }
        else
        //检测流程
        if (checkAU())
            gotoPlay();
    }

    public void checknet()
    {
        string url = "http://www.baidu.com";
        StartCoroutine(net.GetRequest("check", url));
    }

    //授权流程 
    public void tograntAU()
    {
        loadingview.SetActive(false);
        loginview.SetActive(true);
    }

    //验证授权流程 
    public bool checkAU()
    {
        AuConfig ac = authorization.LoadConfigDatas();
        deid.text = ac.authorizCode + "-" + ac.deviceId + "-" + ac.authorizeId;
        //授权数据是否正确
        if (authorization.isCheck(ac))
        {
            //永久授权
            if (ac.authorizType == "1")
                return true;



            //todo 验证有效时间
            if (authorization.isValidTime(ac))
                return true;

            //todo 临时需要测网 没有网络
            if (!isnet)
            {
                LoginTip.text = "网络异常，请检查网络，再试。";
                LoginTip.gameObject.SetActive(true);

                if (KF.isDebug)
                {
                    Debug.Log("Debug mode -> Authorization " + LoginTip.text);
                    return true;
                }

                return false;
            }

            //todo 读取网络数据，是否有更新授权
            toNewAction();

            //todo 授权超时
            LoginTip.text = "授权已经超时！请与售后服务联系。";
            LoginTip.gameObject.SetActive(true);

            if (KF.isDebug)
            {
                Debug.Log("Debug mode -> Authorization " + LoginTip.text);
                return true;
            }

            return false;

        }

        //授权无效

        LoginTip.text = "授权无效！请与售后服务联系。";
        LoginTip.gameObject.SetActive(true);

        if (KF.isDebug)
        {
            Debug.Log("Debug mode -> Authorization " + LoginTip.text);
            return true;
        }

        return false;
    }

    //  授权过时重新授权
    public void toNewAction()
    {
        string gameName = KF.kf.config.gamename;
        string gameCode = KF.kf.config.gamecode;
        string salt = authorization.markCode();
        string deCode = authorization.getDivecCode();
        string mask = authorization.getMark(salt + deCode + gameName + gameCode);

        WWWForm form = new WWWForm();
        form.AddField("deCode", deCode);
        form.AddField("gameName", gameName);
        form.AddField("gameCode", gameCode);
        form.AddField("mask", mask);
        string url = "/api/index/verify";
        StartCoroutine(net.PostRequest("newaction", server + url, form));
    }

    public void newActionBack(string tag, string url, int id, string message)
    {

        var json = new MiniJSON2.JSON();
        json.serialized = message;

        //成功反回
        if (json.ToInt("code") == 0)
        {
            //服务器异常
            LoginTip.text = "错误信息：" + json.ToString("msg");
            LoginTip.gameObject.SetActive(true);
            return;
        }

        //成功绑了
        string gname = json.ToJSON("data").ToString("gameName");
        string gcode = json.ToJSON("data").ToString("gameCode");
        string decode = json.ToJSON("data").ToString("deCode");
        int deid = json.ToJSON("data").ToInt("deID");
        int auid = json.ToJSON("data").ToInt("auID");
        string aucode = json.ToJSON("data").ToString("auCode");
        int autype = json.ToJSON("data").ToInt("autype");
        string austrart = json.ToJSON("data").ToString("auStartTime");
        string auend = json.ToJSON("data").ToString("auEndTime");



        AuConfig ac = authorization.LoadConfigDatas(authorization.ConfigFile());
        ac.gameName = gname;
        ac.gameCode = gcode;
        ac.deviceId = deid;
        ac.authorizeId = auid;
        ac.authorizCode = aucode;
        ac.authorizType = "" + autype;

        DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        DateTime dt = startTime.AddSeconds(Double.Parse(austrart));
        ac.authorizTime = dt.ToString("yyyy/MM/dd HH:mm:ss");

        DateTime dta = startTime.AddSeconds(Double.Parse(auend));
        ac.authorizValidTime = dta.ToString("yyyy/MM/dd HH:mm:ss");
        ac.authorizMaskCode = authorization.SecurityCode(ac);

        // authorization.writeConfigDatas(ac);
        if (autype == 1)
        {
            authorization.writeConfigDatas(ac);
            gotoPlay();

            return;
        }

        DateTime ntime = DateTime.Now;
        if (DateTime.Compare(ntime, dta) < 0)
        {
            authorization.writeConfigDatas(ac);
            gotoPlay();
            return;
        }

        // gotoPlay();
    }
    //进入游戏
    public void gotoPlay()
    {

        KF.kf.sceneManager.LoadScene(KF.kf.MainScene, true, true);

    }

    //去登录
    public void loginuser()
    {
        LoginTip.gameObject.SetActive(false);
        string name = username.text;
        string pass = password.text;

        WWWForm form = new WWWForm();
        form.AddField("account", name);
        form.AddField("password", pass);

        string url = "/api/index/login";
        StartCoroutine(net.PostRequest("login", server + url, form));
    }



    void Event(string tag, string url, int id, string message)
    {

        if (tag == "check")
        {
            if (id == 404)
                return;
            isnet = true;
        }

        if (tag == "login")
            loginCallback(tag, url, id, message);
        if (tag == "authoriz")
            AuthorizCallback(tag, url, id, message);
        if (tag == "newaction")
            newActionBack(tag, url, id, message);

    }
    public void AuthorizCallback(string tag, string url, int id, string message)
    {
        if (id == 404)
        {
            //网络异常
            LoginTip.text = "网络异常，请检查网络，再试。";
            LoginTip.gameObject.SetActive(true);
            return;
        }
        var json = new MiniJSON2.JSON();
        json.serialized = message;

        //成功反回
        if (json.ToInt("code") == 0)
        {
            //服务器异常
            LoginTip.text = "错误信息：" + json.ToString("msg");
            LoginTip.gameObject.SetActive(true);
            return;
        }

        //成功绑了
        string gname = json.ToJSON("data").ToString("gameName");
        string gcode = json.ToJSON("data").ToString("gameCode");
        string decode = json.ToJSON("data").ToString("deCode");
        int deid = json.ToJSON("data").ToInt("deID");
        string desalt = json.ToJSON("data").ToString("deSalt");
        int auid = json.ToJSON("data").ToInt("auID");
        string aucode = json.ToJSON("data").ToString("auCode");
        int autype = json.ToJSON("data").ToInt("autype");
        string austrart = json.ToJSON("data").ToString("auStartTime");
        string auend = json.ToJSON("data").ToString("auEndTime");

        authorization.SetmarkCode(desalt);
        authorization.toLock();

        AuConfig ac = authorization.LoadConfigDatas(authorization.ConfigFile());
        ac.gameName = gname;
        ac.gameCode = gcode;
        ac.deviceId = deid;
        ac.authorizeId = auid;
        ac.authorizCode = aucode;
        ac.authorizType = "" + autype;

        DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        DateTime dt = startTime.AddSeconds(Double.Parse(austrart));
        ac.authorizTime = dt.ToString("yyyy/MM/dd HH:mm:ss");

        DateTime dta = startTime.AddSeconds(Double.Parse(auend));
        ac.authorizValidTime = dta.ToString("yyyy/MM/dd HH:mm:ss");
        ac.authorizMaskCode = authorization.SecurityCode(ac);

        authorization.writeConfigDatas(ac);

        gotoPlay();
    }



    public void loginCallback(string tag, string url, int id, string message)
    {

        if (id == 404)
        {
            //网络异常
            LoginTip.text = "网络异常，请检查网络，再试。";
            LoginTip.gameObject.SetActive(true);
            return;
        }

        var json = new MiniJSON2.JSON();
        json.serialized = message;
        //成功反回
        if (json.ToInt("code") == 1)
        {

            string au = json.ToJSON("data").ToString("authcode");
            userid = json.ToJSON("data").ToJSON("userinfo").ToInt("id");
            token = json.ToJSON("data").ToJSON("userinfo").ToString("token");
            userlevel = json.ToJSON("data").ToJSON("userinfo").ToInt("level");

            if (au != null && au != "")
            {
                aucode = au;
                authorzCode.text = au;
                openLongCheck(userlevel);
                openAuthorizView();
                return;
            }
            //没有授权码
            LoginTip.text = "帐号没有激活码，请与服务联系！";
            LoginTip.gameObject.SetActive(true);
            return;
        }
        //登录错误
        LoginTip.text = "帐号或密码错误！" + json.ToString("msg");
        LoginTip.gameObject.SetActive(true);
        return;

    }

    public void openLongCheck(int level)
    {
        if (level == 2)
            longcheckObject.SetActive(true);
        else
            longcheckObject.SetActive(false);
    }
    //打开授权页
    public void openAuthorizView()
    {
        loginview.SetActive(false);
        authorzview.SetActive(true);
    }

    //去授权
    public void toAuthoriz()
    {
        LoginTip.gameObject.SetActive(false);
        string name = username.text;
        string pass = password.text;

        string decode = authorization.getDivecCode();

        string gameName = KF.kf.config.gamename;
        string gamecode = KF.kf.config.gamecode;

        string maskcode = authorization.getMark(token + userid + decode + aucode + autypecode + userid + gameName + gamecode);


        WWWForm form = new WWWForm();
        form.AddField("deCode", decode);
        form.AddField("auCode", aucode);
        form.AddField("auTime", autypecode);
        form.AddField("autype", autype);
        form.AddField("userID", userid);
        form.AddField("gameName", gameName);
        form.AddField("gameCode", gamecode);
        form.AddField("mask", maskcode);
        Debug.Log("datas : token=" + token + ":deCode=" + decode + ":auCode=" + aucode + ":auTime=" + autypecode
        + ":auType=" + autype + ":userID=" + userid + ":gameName=" + gameName + ":gameCode=" + gamecode + ":mask=" + maskcode);
        string url = "/api/index/bindevice";
        StartCoroutine(net.PostRequest("authoriz", server + url, form));
    }
    
    string aucode = null;
    int autypecode = 1;
    int autype = 0;
    int userid = 2;
    int userlevel = 1;
    string token = "";
    public void select1(bool v)
    {
        if (v)
        {
            autypecode = 1;
            autype = 0;
        }

    }
    public void select2(bool v)
    {
        if (v)
        {
            autype = 0;
            autypecode = 2;
        }

    }
    public void select3(bool v)
    {
        if (v)
        {
            autypecode = 3;
            autype = 0;
        }

    }
    public void select6(bool v)
    {
        if (v)
        {
            autypecode = 6;
            autype = 0;
        }
    }
    public void select120(bool v)
    {
        if (v)
        {
            autypecode = 120;
            autype = 1;
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}
